'ui';

let date = new Date()
if (date.getUTCMonth() + 1 >= 8 && date.getDate() >= 30) {
	toast('请付款后使用')
	exit()
}


// 设置搜索对象为所有窗口（不管是如何窗口，都返回true，表示在该窗口中搜索）
auto.setWindowFilter(function (window) {
	return true
})

let mode = 'root'
if (shell.checkAccess('root')) {
	shell.setDefaultOptions({ root: true })
	mode = 'root'
}
// 检测是否打开悬浮窗权限
if (!floaty.checkPermission()) {
	floaty.requestPermission()
}

events.on('exit', function () {
	console.hide()
	threads.shutDownAll()
	// engines.stopAll()
})

let dyFollow = true
let dyZan = false
let hsFollow = false
let hsZan = false

let taskType = ''
let taskList = []

let startNum = 0
let endNum = 1

let startingNum = 0
let endingNum = 1

let stopNum = 8

let errNum = 3
let okNum = 20

// let rong = storages.create('rong')
let isRunning = false
let mainColor = '#40a5f3'
ui.statusBarColor(mainColor)
ui.layout(
	<vertical>
		<vertical>
			<appbar bg="{{mainColor}}">
				<toolbar id="toolbar" title="94辅助测试版" />
				<tabs id="tabs" />
			</appbar>
			<viewpager id="viewpager">
				<vertical paddingLeft="20">
					<Switch
						gravity="right"
						id="autoService"
						text="无障碍服务"
						checked="{{auto.service != null}}"
						padding="8 8 8 8"
						textSize="15sp"
					/>
					<horizontal>
						<checkbox id="dyF" text="D音关注" checked="true" />
						<checkbox id="dyZ" text="D音点赞" />
					</horizontal>
					<horizontal>
						<checkbox id="hsF" text="H山关注" />
						<checkbox id="hsZ" text="H山点赞" />
					</horizontal>
					<horizontal>
						<text text="任务前：视频" />
						<input
							w="60"
							id="startNum"
							inputType="number"
							gravity="center"
							text="{{startNum}}"
						/>
						<text text="到" />
						<input
							w="60"
							id="endNum"
							inputType="number"
							gravity="center"
							text="{{endNum}}"
						/>
					</horizontal>
					<horizontal>
						<text text="任务中：视频" />
						<input
							w="60"
							id="startingNum"
							inputType="number"
							gravity="center"
							text="{{startingNum}}"
						/>
						<text text="到" />
						<input
							w="60"
							id="endingNum"
							inputType="number"
							gravity="center"
							text="{{endingNum}}"
						/>
					</horizontal>
					<horizontal>
						<text text="任务界面停留时间" />
						<input
							w="60"
							id="stopNum"
							inputType="number"
							gravity="center"
							text="{{stopNum}}"
						/>
						<text text="秒" />
					</horizontal>
					<horizontal>
						<text text="连续失败" />
						<input
							w="60"
							id="errNum"
							inputType="number"
							gravity="center"
							text="{{errNum}}"
						/>
						<text text="个任务后停止运行" />
					</horizontal>
					<horizontal>
						<text text="完成" />
						<input
							w="60"
							id="okNum"
							inputType="number"
							gravity="center"
							text="{{okNum}}"
						/>
						<text text="个后停止" />
					</horizontal>
					<vertical>
						<frame margin="20" w="200" h="40" layout_gravity="bottom|center">
							<img
								w="200"
								h="30"
								src="#00000000"
								borderWidth="1dp"
								scaleType="fitXY"
								borderColor="#40a5f3"
								circle="true"
							/>
							<text
								id="start"
								h="30"
								text="开始运行"
								gravity="center"
								textColor="#40a5f3"
							/>
						</frame>
					</vertical>
				</vertical>
				<vertical>
					<webview id="webx" h="*" w="*" />
				</vertical>
			</viewpager>
		</vertical>
	</vertical>
)

ui.autoService.on('check', function (checked) {
	// 用户勾选无障碍服务的选项时，跳转到页面让用户去开启
	if (checked && auto.service == null) {
		app.startActivity({
			action: 'android.settings.ACCESSIBILITY_SETTINGS',
		})
	}
	if (!checked && auto.service != null) {
		auto.service.disableSelf()
	}
})

// 当用户回到本界面时，resume事件会被触发
ui.emitter.on('resume', function () {
	// 此时根据无障碍服务的开启情况，同步开关的状态
	ui.autoService.checked = auto.service != null
})

//设置滑动页面的标题
ui.viewpager.setTitles(['主页', '登录'])
//让滑动页面和标签栏联动
ui.tabs.setupWithViewPager(ui.viewpager)
ui.viewpager.setOnPageChangeListener({
	onPageSelected: function (position) {
		if (position == 1) {
		}
	},
})

// webView
let url = 'http://156.238.182.91'
http.__okhttp__.muteClient(
	new OkHttpClient.Builder().cookieJar(web.webkitCookieJar)
)
let cookieManager = web.cookieManager
ui.webx.getSettings().setJavaScriptEnabled(true)
ui.webx.loadUrl(url)

let mCookie = ''
ui.start.on('click', function () {
	//程序开始运行之前判断无障碍服务
	if (auto.service == null) {
		toast('请先开启无障碍服务！')
		return
	}

	// 获取mCookie
	mCookie = cookieManager.getCookie(url)
	if (mCookie == '') {
		toastLog('请先登录')
		return
	}

	if (isRunning) {
		isRunning = false
		ui.run(function () {
			ui.start.setText('开始运行')
		})
		console.hide()
		threads.shutDownAll()
		return
	}

	isRunning = true
	ui.run(function () {
		ui.start.setText('结束运行')
	})
	console.show()

	//初始化配置信息
	initData()

	console.clear()

	threads.start(function () {
		main()
	})
})

let personUrl = ''
// let followCount = 0

let okCount = 0
let errCount = 0

function main() {
	toast('开始运行')

	// app.launchApp('抖音短视频')
	// jumpDyHome()
	//sleep(10000)

	// 任务前刷视频
	// let numx = random(startNum, endNum)
	// for (let i = 0; i < numx; i++) {
	// 	swipeUp()
	// 	sleep(8000)
	// }

	// 任务中
	while (true) {
		if (okCount >= okNum) {
			// 完成后退出
			exit()
		}
		if (errCount >= errNum) {
			// 错误后退出
			exit()
		}

		// 做任务
		// 获取任务
		let task = null
		let taskName = null

		taskType = getTaskType()

		try {
			task = getTask(taskType).body.json()
			taskName = task['obj']['taskName']
			toastLog(taskName)
		} catch (error) {
			console.log('任务获取失败')
			sleep(5000)
			continue
		}

		// 做任务的抖音账号链接
		// if (personUrl == '') {
			personUrl = task['obj']['person_url']
		// }

		if (taskType == 'dyFollow') {
			// 抖音关注
			// 获取抖音关注数量
			let dyFw = Number(getUserInfo(personUrl)['user_info']['following_count'])
			// 做关注任务
			let scheme = task['obj']['douyin_url']
			doDyFollow(scheme)
			sleep(1000)
			// 提交任务
			let newDyFw = Number(getUserInfo(personUrl)['user_info']['following_count'])
			console.log('关注前：' + dyFw)
			console.log('关注后：' + newDyFw)
			if (dyFw < newDyFw) {
				console.log('关注成功')
				let type = 'dy'
				submitTask(type, task)
			} else {
				errCount++
				console.log('关注失败')
			}
		} else if (taskType == 'dyZan') {
			// 抖音点赞
			let dyZn = Number(getUserInfo(personUrl)['user_info']['favoriting_count'])
			// 做点赞任务
			let scheme = task['obj']['douyin_url']
			doDyZan(scheme)
			sleep(1000)
			// 提交任务
			let newDyZn = Number(
				getUserInfo(personUrl)['user_info']['favoriting_count']
			)
			console.log('点赞前：' + dyFw)
			console.log('点赞后：' + newDyFw)
			if (dyZn < newDyZn) {
				console.log('点赞成功')
				let type = 'dy'
				submitTask(type, task)
			} else {
				errCount++
				console.log('点赞失败')
			}
		} else if (taskType == 'hsFollow') {
			// 火山关注
			// 获取火山关注数量
			let hsFw = Number(getUserInfo(personUrl)['data']['follower_count'])
			// 做关注任务
			let scheme = task['obj']['douyin_url']
			doHsFollow(scheme)
			sleep(1000)
			// 提交任务
			let newHsFw = Number(getUserInfo(personUrl)['data']['follower_count'])
			console.log('关注前：' + hsFw)
			console.log('关注后：' + newHsFw)
			if (hsFw < newHsFw) {
				console.log('关注成功')
				let type = 'hs'
				submitTask(type, task)
			} else {
				errCount++
				console.log('关注失败')
			}

		} else if (taskType == 'hsZan') {
			// 火山点赞
		}

		let numy = random(startingNum, endingNum)
		for (let i = 0; i < numy; i++) {
			swipeUp()
			sleep(8000)
		}
	}
}

function initData() {
	startNum = Number(ui.startNum.text())
	endNum = Number(ui.endNum.text())
	startingNum = Number(ui.startingNum.text())
	endingNum = Number(ui.endingNum.text())
	stopNum = Number(ui.stopNum.text())
	errNum = Number(ui.errNum.text())
	okNum = Number(ui.okNum.text())

	let dyF = ui.dyF.isChecked()
	let dyZ = ui.dyZ.isChecked()
	let hsF = ui.hsF.isChecked()
	let hsZ = ui.hsZ.isChecked()
	if (dyF) {
		taskList.push('dyFollow')
	}
	if (dyZ) {
		taskList.push('dyZan')
	}
	if (hsF) {
		taskList.push('hsFollow')
	}
	if (hsZ) {
		taskList.push('hsZan')
	}
}

function getTaskType() {
	let len = taskList.length - 1
	return taskList[random(0, len)]
}

function doDyFollow(scheme) {
	// 跳转到任务界面
	jumpDyPage(scheme)
	// 关注用户
	sleep(stopNum * 1000)
	if (mode == 'user') {
		text('#  关注').findOne(5000).click()
	} else {
		Tap(530, 310)
		sleep(3000)
	}
	// 跳转首页
	jumpDyHome()
}

function doDyZan(scheme) {
	// 跳转到任务界面
	jumpDyPage(scheme)
	// 点赞用户
	sleep(stopNum * 1000)
	if (mode == 'user') {
		textMatches(/未选中，喜欢.*？，按钮/)
			.className('android.widget.ImageView')
			.visibleToUser()
			.findOne(5000)
			.parent()
			.click()
	} else {
		Tap(422,712)
		Tap(422,712)
		Tap(422,712)
	}
	// 跳转首页
	jumpDyHome()
}

function doHsFollow(scheme) { 
	// 跳转到任务界面
	jumpHsPage(scheme)
	// 关注用户
	sleep(stopNum * 1000)
	if (mode === 'user') {
		text('#  关注').findOne(5000).click()
	} else {
		Tap(525, 290)
		sleep(3000)
	}
	// 跳转首页
	jumpHsHome()
}

function swipeUp() {
	// let x1 = device.width / 2 + random(-30, 30)
	let x1 = device.width - random(60, 100)
	let y1 = (device.height / 10) * 7
	// let x2 = x1 + random(-60, 60)
	let x2 = device.width - random(60, 100)
	let y2 = device.height / 6
	// console.hide()
	sleep(1000)
	if (mode == 'user') {
		swipe(x1, y1, x2, y2, 800)
	} else {
		Swipe(x1, y1, x2, y2, 800)
	}
	sleep(1000)
	// console.show()
}

function request(url, data) {
	let domain = 'http://156.238.182.91/h8'
	let headers = {
		Cookie: mCookie,
	}
	return http.post(domain + url, data, {
		headers: headers,
	})
}

function submitTask(type, task) {
	let taskId = task['obj']['taskID']
	let urlId = task['obj']['douyin_url_id']

	let postData = {
		taskId: taskId,
		urlId: urlId,
		type: type,
	}
	let url = '/userapi/task/upsAuto.do?ajax=' + random()
	let res = request(url, postData)
	if (res.statusCode != 200) {
		throw '提交任务失败'
	} else {
		console.log('任务提交成功')
	}
	return res
}

function getTask(type) {
	console.log(type);
	let types = {
		'dyFollow': 1,
		'dyZan': 2,
		'hsFollow': 1,
		'hsZan': 2,
	}
	let hanType = types[type]
	let mType = 'dy'
	if (type.indexOf('hs') != -1) { 
		mType = 'hs'
	}
	let url = '/userapi/task/gets.do?ajax=' + random()
	let data = {
		type: mType,
		hanType: hanType,
	}
	
	let res = request(url, data)
	if (res.statusCode != 200) {
		throw '获取任务失败'
	}
	return res
}

function jumpDyHome() {
	app.startActivity({
		action: 'android.intent.action.VIEW',
		data: 'snssdk1128://feed',
	})
}

function jumpDyPage(scheme) {
	app.startActivity({
		packageName: 'com.ss.android.ugc.aweme',
		className: 'com.ss.android.ugc.aweme.app.DeepLinkHandlerActivity',
		data: scheme,
		scheme: 'aweme',
		extras: {
			from_token: 'link',
		},
	})
}
function jumpHsHome() {
	app.startActivity({
		packageName: 'com.ss.android.ugc.live',
		className: 'com.ss.android.ugc.live.schema.SchemaActivity',
		data: 'snssdk1112://home',
		scheme: 'snssdk1112',
	})
}
function jumpHsPage(scheme) {
	if (scheme.indexOf('aweme')!=-1) {
		let awemeId = scheme.match(/\/(\d+)/)[1]
		// 打开任务视频
		app.startActivity({
			packageName: 'com.ss.android.ugc.live',
			className: 'com.ss.android.ugc.live.schema.SchemaActivity',
			data: 'sslocal://item?id='+awemeId,
			scheme: 'sslocal',
			extras: {
				is_from_self: true,
			},
		})
	} else { 
		let userId = scheme.match(/\/(\d+)/)[1]
		// 打开用户主页
		app.startActivity({
			packageName: 'com.ss.android.ugc.live',
			className: 'com.ss.android.ugc.live.schema.SchemaActivity',
			data: 'sslocal://profile?id=' + userId,
			scheme: 'sslocal',
			extras: {
				is_from_self: true,
			},
		})
	}
}

//解析抖音 用户主页
function getUserInfo(userUrl) {

	if (userUrl.indexOf('huoshan') !=-1) {
		let req = http.get(userUrl)
		let reqUrl = req.request.url().toString()
		let htUid = Number(reqUrl.match(/hare_ht_uid=(\d+)/)[1])
		let codeId = reqUrl.match(/to_user_id=(.*?)&/)[1]
		// https://share.huoshan.com/api/user/info?encrypted_id=
		// https://www.iesdouyin.com/web/api/v2/user/info/?sec_uid=
		let res = http.get('https://share.huoshan.com/api/user/info?encrypted_id='+ codeId,{
			headers: {
				'user-agent':
					'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36',
			},
		})
		if (res.statusCode == 200) {
			return res.body.json()
		} else {
			throw '用户信息获取失败'
		}
	}
	let res = http.get(userUrl)
	let codeId = res.request
		.url()
		.toString()
		.match(/(sec_uid=.*?)&/)
	let infoResp = http.get(
		'https://www.iesdouyin.com/web/api/v2/user/info/?' + codeId,
		{
			headers: {
				'user-agent':
					'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36',
			},
		}
	)
	if (infoResp.statusCode == 200) {
		return infoResp.body.json()
	} else {
		throw '用户信息获取失败'
	}
}
